import 'dart:async';
import 'dart:io';
import 'dart:math' as math;
import 'dart:isolate';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/chunk_upload.dart';
import '../services/upload/chunk_upload_service.dart';
import '../riverpod/photo_backup_notifier.dart';
import 'package:photo_manager/photo_manager.dart';
import 'dart:typed_data';
import '../services/asset_cache_service.dart';
import '../services/photo_backup_service.dart';
import '../config/config_loader.dart';

// 创建PhotoBackupService的Provider
final photoBackupServiceProvider = Provider<PhotoBackupService>((ref) {
  return PhotoBackupService();
});

class UploadDetailPage extends ConsumerStatefulWidget {
  const UploadDetailPage({Key? key}) : super(key: key);

  @override
  ConsumerState<UploadDetailPage> createState() => _UploadDetailPageState();
}

class _UploadDetailPageState extends ConsumerState<UploadDetailPage> {
  Key _streamKey = UniqueKey();
  List<AssetEntity> _recentAssets = [];
  bool _isLoading = true;
  final AssetCacheService _assetCacheService = AssetCacheService();
  final PhotoBackupService _photoBackupService = PhotoBackupService();
  bool _isBackgroundLoading = false;

  // 自动刷新计时器
  Timer? _autoRefreshTimer;

  // 添加一个权限状态变量
  bool _hasPhotoPermission = false;

  // 检查照片权限
  Future<void> _checkPhotoPermission() async {
    final permissionStatus = await PhotoManager.requestPermissionExtend();
    if (mounted) {
      setState(() {
        _hasPhotoPermission = permissionStatus.isAuth;
        if (!_hasPhotoPermission) {
          _isLoading = false; // 如果没有权限，停止加载
          debugPrint('没有照片访问权限: ${permissionStatus.toString()}');
        } else {
          // 如果有权限，并且之前没有加载过，开始加载
          if (_recentAssets.isEmpty && !_isLoading) {
            _isLoading = true;
            // 需要在setState之后再加载，避免状态冲突
            Future.microtask(() => _loadRecentFiles());
          }
        }
      });
    }
  }

  @override
  void initState() {
    super.initState();

    // 第一次加载资源文件
    _loadRecentFiles();

    // 延迟打印调试信息，避免启动时卡顿 - 使用更长的延迟
    Future.delayed(const Duration(milliseconds: 800), () {
      if (mounted) {
        _printDebugInfo();
      }
    });

    // 先设置上传任务完成监听 - 这个操作较轻量，可以立即执行
    _setupUploadCompletionListener();

    // 分步执行权限检查和加载文件
    Future.microtask(() async {
      // 先检查权限
      await _checkPhotoPermission();

      // 短暂延迟，让UI有时间响应
      await Future.delayed(const Duration(milliseconds: 50));

      // 有权限后再加载文件
      if (_hasPhotoPermission && mounted) {
        _loadRecentFiles();
      }
    });

    // 添加超时处理，防止加载状态无限持续
    Future.delayed(const Duration(seconds: 10), () {
      if (mounted && _isLoading) {
        debugPrint('加载超时，强制结束加载状态');
        setState(() {
          _isLoading = false;
        });
      }
    });
  }

  @override
  void dispose() {
    _autoRefreshTimer?.cancel();
    super.dispose();
  }

  // 加载相册中的最新文件
  Future<void> _loadRecentFiles() async {
    // 不再直接返回，而是检查是否为首次加载
    // 如果不是首次加载且正在加载中，则返回
    if (_isLoading && _recentAssets.isNotEmpty) return;

    setState(() {
      _isLoading = true;
    });

    try {
      // 清除缓存，确保获取最新数据
      _assetCacheService.clearCache();

      // 加载待备份资产
      await _loadPendingBackupAssets();

      // 更新UI
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }

      // 检查是否需要启动自动备份
      await _startAutoBackupIfEnabled();
    } catch (e) {
      debugPrint('加载最近文件失败: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });

        // 显示错误信息
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              '加载文件失败: ${e.toString().substring(0, math.min(50, e.toString().length))}',
            ),
          ),
        );
      }
    }
  }

  // 加载待备份资产时优化缩略图处理
  Future<void> _loadPendingBackupAssets() async {
    debugPrint('获取待备份资产');

    if (!mounted) return;

    try {
      // 确保有相册访问权限
      final permissionStatus = await PhotoManager.requestPermissionExtend();
      if (permissionStatus.isAuth != true) {
        debugPrint('没有相册访问权限：${permissionStatus.toString()}');
        if (mounted) {
          setState(() {
            _recentAssets = [];
            _isLoading = false;
          });
        }
        return;
      }

      // 直接使用 PhotoBackupService 获取待备份资产
      // 这利用了现有的断点续传和去重机制
      final backupState = ref.read(photoBackupProvider);

      // 检查是否有选中的相册
      final hasSelectedAlbums = backupState.selectedAlbums.values.any(
        (selected) => selected,
      );
      if (!hasSelectedAlbums) {
        debugPrint('没有选中的相册，显示空列表');
        if (mounted) {
          setState(() {
            _recentAssets = [];
            _isLoading = false;
          });
        }
        return;
      }

      // 通过超时保护，确保不会无限等待
      final resultCompleter = Completer<List<AssetEntity>>();

      // 设置超时保护
      Future.delayed(const Duration(seconds: 15), () {
        if (!resultCompleter.isCompleted) {
          debugPrint('获取待备份资产超时，返回空列表');
          resultCompleter.complete([]);
        }
      });

      // 在后台线程中执行耗时操作
      Future.microtask(() async {
        try {
          // 获取待备份资产，减少数量以提高加载速度
          final pendingAssets = await _photoBackupService
              .getPendingBackupAssets(
                ref,
                limit: 10, // 进一步减少数量，提高加载速度
              );
          if (!resultCompleter.isCompleted) {
            resultCompleter.complete(pendingAssets);
          }
        } catch (e) {
          if (!resultCompleter.isCompleted) {
            debugPrint('获取待备份资产失败: $e');
            resultCompleter.complete([]);
          }
        }
      });

      // 等待结果
      final pendingAssets = await resultCompleter.future;
      debugPrint('获取到${pendingAssets.length}个待备份资产');

      // 保存到缓存
      if (pendingAssets.isNotEmpty) {
        _assetCacheService.addAssets(pendingAssets);
      }

      // 预加载缩略图 - 限制并发数量，并使用低质量缩略图
      if (pendingAssets.isNotEmpty) {
        Future.microtask(() {
          // 使用批处理方式加载缩略图，避免一次性加载过多
          _preloadThumbnailsBatch(pendingAssets);
        });
      }

      // 更新UI
      if (mounted) {
        setState(() {
          _recentAssets = pendingAssets;
          _isLoading = false;
        });
      }
    } catch (e) {
      debugPrint('获取待备份资产失败 (外部异常): $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  // 分批预加载缩略图，控制并发数量
  Future<void> _preloadThumbnailsBatch(List<AssetEntity> assets) async {
    // 每批处理的资产数量
    const int batchSize = 3;
    // 低质量缩略图大小
    const int thumbnailSize = 150; // 缩小尺寸以减少内存占用和处理时间

    for (int i = 0; i < assets.length; i += batchSize) {
      // 如果组件被销毁，停止加载
      if (!mounted) break;

      // 计算当前批次的结束索引
      final int end =
          (i + batchSize < assets.length) ? i + batchSize : assets.length;
      // 获取当前批次的资产
      final batch = assets.sublist(i, end);

      // 使用微任务处理每个批次，避免阻塞UI
      await Future.microtask(() async {
        for (final asset in batch) {
          try {
            // 如果已经有缓存，跳过
            if (_assetCacheService.hasThumbnail(asset.id)) continue;

            // 使用较低质量的缩略图
            final thumbData = await asset.thumbnailDataWithSize(
              ThumbnailSize(thumbnailSize, thumbnailSize),
              quality: 70, // 降低质量以加快处理速度
            );

            if (thumbData != null && mounted) {
              _assetCacheService.addThumbnail(asset.id, thumbData);
            }

            // 每处理一个缩略图后短暂暂停，让UI有机会响应
            await Future.delayed(const Duration(milliseconds: 5));
          } catch (e) {
            debugPrint('预加载缩略图失败: ${asset.id}, 错误: $e');
          }
        }
      });

      // 批次之间添加短暂延迟，避免连续处理导致UI卡顿
      await Future.delayed(const Duration(milliseconds: 50));
    }
  }

  // 在后台刷新数据
  Future<void> _refreshDataInBackground() async {
    if (_isBackgroundLoading) return;

    setState(() {
      _isBackgroundLoading = true;
    });

    try {
      await _loadPendingBackupAssets();

      // 如果有新数据且界面仍然挂载，更新UI
      if (mounted) {
        setState(() {
          _recentAssets = List.from(_assetCacheService.cachedAssets);
          _isBackgroundLoading = false;
        });

        // 检查自动备份并启动
        _startAutoBackupIfEnabled();
      }
    } catch (e) {
      debugPrint('后台刷新数据失败: $e');
      if (mounted) {
        setState(() {
          _isBackgroundLoading = false;
        });
      }
    }
  }

  // 检查并启动自动备份 - 优化以防止ANR
  Future<void> _startAutoBackupIfEnabled() async {
    // 获取备份状态
    if (!mounted) return;

    // 使用compute或isolate执行耗时操作
    try {
      // 使用单独的线程处理上传逻辑，避免阻塞UI
      Future(() async {
        final backupState = ref.read(photoBackupProvider);

        // 检查自动备份是否已开启
        if (!_photoBackupService.isAutoBackupEnabled(backupState)) {
          debugPrint(
            '自动备份未启用: 照片备份=${backupState.autoBackupPhotos}, 视频备份=${backupState.autoBackupVideos}',
          );
          return;
        }

        // 已经在上传中，不启动新的上传
        if (_photoBackupService.isBackingUp) {
          debugPrint('上传任务已经在进行中，不启动新任务');
          return;
        }

        // 设置一个超时保护，避免永久阻塞
        final getAssetsCompleter = Completer<List<AssetEntity>>();

        // 超时保护 - 缩短超时时间，避免长时间阻塞
        Future.delayed(const Duration(seconds: 3), () {
          if (!getAssetsCompleter.isCompleted) {
            debugPrint('获取待备份资产超时，设为空列表');
            getAssetsCompleter.complete([]);
          }
        });

        // 在后台获取待备份资产
        try {
          debugPrint('准备获取待备份资产...');
          // 减少获取的资产数量，优先处理少量资产，降低内存和处理压力
          final pendingAssets = await _photoBackupService
              .getPendingBackupAssets(
                ref,
                limit: 5, // 减少数量，防止一次性处理太多
              );

          if (!getAssetsCompleter.isCompleted) {
            getAssetsCompleter.complete(pendingAssets);
          }
        } catch (e) {
          debugPrint('获取待备份资产失败: $e');
          if (!getAssetsCompleter.isCompleted) {
            getAssetsCompleter.complete([]);
          }
        }

        // 等待结果
        final pendingAssets = await getAssetsCompleter.future;
        debugPrint('获取到${pendingAssets.length}个待备份资产');

        // 没有待备份的资产
        if (pendingAssets.isEmpty) {
          debugPrint('没有找到待备份的资产，不启动上传');
          return;
        }

        // 开始批量上传，确保在widget被销毁后不会使用ref
        if (mounted) {
          debugPrint('开始批量上传${pendingAssets.length}个资产');

          try {
            await _photoBackupService.startBatchUpload(ref, pendingAssets);
            debugPrint('批量上传已启动');

            // 强制刷新界面以显示进度，使用Handler或EventChannel避免直接setState
            if (mounted) {
              // 使用事件分离UI更新和后台任务
              Future.microtask(() {
                if (mounted) {
                  setState(() {
                    _streamKey = UniqueKey();
                  });
                }
              });
            }
          } catch (e) {
            debugPrint('启动批量上传失败: $e');
          }
        }
      });
    } catch (e) {
      debugPrint('检查自动备份时出错: $e');
    }
  }

  // 设置上传任务完成监听 - 优化以避免ANR
  void _setupUploadCompletionListener() {
    // 监听间隔时间，避免太频繁处理导致卡顿
    int lastProcessTime = 0;

    // 使用节流控制事件处理频率
    ChunkUploadService.uploadTasksStream.listen((tasks) {
      if (!mounted) return;

      // 严格控制事件处理频率，避免过于频繁更新导致UI卡顿
      // 增加间隔时间到1000毫秒，进一步减少处理频率
      final now = DateTime.now().millisecondsSinceEpoch;
      if (now - lastProcessTime < 1000) {
        // 至少间隔1秒处理一次，大幅减少事件处理频率
        return;
      }
      lastProcessTime = now;

      // 使用独立线程处理数据分析，完全脱离UI线程
      Future(() {
        if (!mounted) return;

        try {
          // 使用安全的数据副本进行处理，避免并发修改问题
          final tasksCopy = List<UploadTask>.from(tasks);

          // 计算已完成任务数量
          final completedCount =
              tasksCopy
                  .where((task) => task.status == UploadTaskStatus.completed)
                  .length;

          // 计算活跃任务数量（上传中或等待中）
          final activeCount =
              tasksCopy
                  .where(
                    (task) =>
                        task.status == UploadTaskStatus.uploading ||
                        task.status == UploadTaskStatus.pending,
                  )
                  .length;

          // 检查是否有失败的任务，失败任务不应触发添加新资产
          final failedTasks =
              tasksCopy
                  .where((task) => task.status == UploadTaskStatus.failed)
                  .toList();

          if (failedTasks.isNotEmpty) {
            // 有失败任务，记录日志但不添加新任务
            // 限制处理失败任务的数量，避免日志过多
            for (var task in failedTasks.take(3)) {
              debugPrint('检测到失败任务: ${task.fileName}, 不添加新资产');
            }
            if (failedTasks.length > 3) {
              debugPrint('...还有 ${failedTasks.length - 3} 个失败任务未显示');
            }
            return;
          }

          // 如果活跃任务数量小于最大并行数，尝试添加新资产到队列
          if (activeCount < ref.read(photoBackupProvider).parallelBackupCount) {
            // 计算需要添加的新资产数量：最大并行数 - 活跃任务数
            final neededCount =
                ref.read(photoBackupProvider).parallelBackupCount - activeCount;

            if (neededCount > 0 && _photoBackupService.isBackingUp) {
              debugPrint('检测到任务完成，尝试添加$neededCount个新资产到队列');

              // 使用完全独立的线程添加新资产，确保不影响UI
              Future(() async {
                try {
                  await _photoBackupService.addNewAssetsToQueue(
                    ref,
                    neededCount,
                  );

                  // 控制刷新频率，避免频繁的UI更新
                  if (mounted) {
                    // 使用随机延迟，避免多个更新同时触发
                    final randomDelay =
                        300 + math.Random().nextInt(700); // 300-1000毫秒随机延迟

                    Future.delayed(Duration(milliseconds: randomDelay), () {
                      if (mounted) {
                        Future.microtask(() {
                          _refreshDataInBackground();
                        });
                      }
                    });
                  }
                } catch (e) {
                  debugPrint('添加新资产到队列失败: $e');
                }
              });
            }
          }
        } catch (e) {
          debugPrint('处理上传完成事件时出错: $e');
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    final photoBackupState = ref.watch(photoBackupProvider);
    final totalCount = _calculateTotalFiles(photoBackupState);

    return Scaffold(
      appBar: AppBar(
        title: const Text('备份详情'),
        actions: [
          // 添加调试按钮
          IconButton(
            icon: const Icon(Icons.bug_report),
            onPressed: _showDebugOptions,
            tooltip: '调试选项',
          ),
        ],
      ),
      body: Column(
        children: [
          // 顶部进度信息
          _buildProgressInfo(totalCount),

          // 主体内容 - 使用Expanded包裹，避免内容溢出
          Expanded(
            child: RefreshIndicator(
              onRefresh: _refreshData,
              // 为了更好的性能，使用ListView.builder，而不是标准ListView
              child:
                  !_hasPhotoPermission || _isLoading
                      ? _buildPlaceholderContent() // 显示权限或加载提示
                      : _buildOptimizedList(), // 使用优化的列表构建方法
            ),
          ),
        ],
      ),
    );
  }

  // 构建优化的列表，使用ListView.builder实现懒加载
  Widget _buildOptimizedList() {
    // 获取活动任务 - 限制数量以提高性能
    final activeTasks =
        ChunkUploadService.uploadTasks
            .where(
              (task) =>
                  task.status == UploadTaskStatus.pending ||
                  task.status == UploadTaskStatus.uploading ||
                  task.status == UploadTaskStatus.paused,
            )
            .take(20) // 限制最多显示20个任务
            .toList();

    // 限制项目数量，避免渲染太多导致卡顿
    final limitedAssets = _recentAssets.take(20).toList(); // 最多显示20个待备份资产

    // 如果没有任何内容，显示空状态
    if (limitedAssets.isEmpty && activeTasks.isEmpty) {
      return _buildEmptyStateContent();
    }

    // 合并活动任务和待上传资产，创建一个组合列表
    final List<Widget> items = [];

    // 添加统一标题
    items.add(
      const Padding(
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: Text(
          '备份文件',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: Colors.black,
          ),
        ),
      ),
    );

    // 添加上传中的任务
    for (var task in activeTasks) {
      items.add(_buildCombinedTaskItem(task));
    }

    // 添加待上传文件(过滤掉已经在上传的文件)
    for (var asset in limitedAssets) {
      // 检查资产是否已经在上传任务中 - 使用文件名比较
      bool isAlreadyInQueue = activeTasks.any(
        (task) => (asset.title != null && task.fileName == asset.title),
      );

      if (!isAlreadyInQueue) {
        items.add(_buildAssetItem(asset));
      }
    }

    // 如果有更多资产，显示提示
    if (_recentAssets.length > limitedAssets.length) {
      items.add(
        Padding(
          padding: const EdgeInsets.all(16),
          child: Center(
            child: Text(
              '还有 ${_recentAssets.length - limitedAssets.length} 个文件未显示',
              style: TextStyle(color: Colors.grey.shade600),
            ),
          ),
        ),
      );
    }

    // 返回ListView.builder，利用懒加载特性
    return ListView.builder(
      itemCount: items.length,
      // 使用cacheExtent来预加载更多项目，提高滑动体验
      cacheExtent: 200,
      itemBuilder: (context, index) => items[index],
    );
  }

  // 构建结合了资产视觉风格的上传任务项
  Widget _buildCombinedTaskItem(UploadTask task) {
    // 缓存状态和进度，避免频繁状态计算
    final taskStatus = task.status;
    final fileName = task.fileName ?? '未知文件';
    final fileSize = task.fileSize ?? 0;
    final uploadedBytes = task.uploadedBytes;

    // 计算实际进度比例（0-1之间）
    final actualProgress = fileSize > 0 ? uploadedBytes / fileSize : 0.0;
    final displayValue = math.max(
      (task.progress > 1 ? task.progress / 100 : task.progress).clamp(0.0, 1.0),
      actualProgress.clamp(0.0, 1.0),
    );

    // 进度文本
    final progressPercent = (displayValue * 100).clamp(0.0, 100.0);
    final displayProgress = progressPercent.toStringAsFixed(1);

    // 状态颜色
    final statusColor =
        {
          UploadTaskStatus.pending: Colors.blue,
          UploadTaskStatus.uploading: Colors.green,
          UploadTaskStatus.paused: Colors.orange,
          UploadTaskStatus.completed: Colors.green,
          UploadTaskStatus.failed: Colors.red,
          UploadTaskStatus.canceled: Colors.grey,
        }[taskStatus] ??
        Colors.grey;

    // 状态文本
    final statusText =
        {
          UploadTaskStatus.pending: '等待上传',
          UploadTaskStatus.uploading: '上传中',
          UploadTaskStatus.paused: '已暂停',
          UploadTaskStatus.completed: '已完成',
          UploadTaskStatus.failed: '上传失败',
          UploadTaskStatus.canceled: '已取消',
        }[taskStatus] ??
        '未知状态';

    // 格式化文件大小
    final formattedSize = _formatFileSize(fileSize);
    final formattedUploadedSize = _formatFileSize(uploadedBytes);

    // 操作按钮 - 移到上面来提前构建
    final actionButtons = Row(
      mainAxisAlignment: MainAxisAlignment.end,
      mainAxisSize: MainAxisSize.min,
      children: [
        // 根据状态显示不同的按钮
        if (taskStatus == UploadTaskStatus.uploading)
          IconButton(
            icon: const Icon(Icons.pause, color: Colors.orange),
            onPressed: () => ChunkUploadService.pauseUploadTask(task.id),
            tooltip: '暂停上传',
            iconSize: 20,
            padding: EdgeInsets.zero,
            constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
          ),
        if (taskStatus == UploadTaskStatus.paused)
          IconButton(
            icon: const Icon(Icons.play_arrow, color: Colors.green),
            onPressed: () => ChunkUploadService.resumeUploadTask(task.id),
            tooltip: '继续上传',
            iconSize: 20,
            padding: EdgeInsets.zero,
            constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
          ),
        if (taskStatus == UploadTaskStatus.pending ||
            taskStatus == UploadTaskStatus.paused ||
            taskStatus == UploadTaskStatus.failed)
          IconButton(
            icon: const Icon(Icons.delete, color: Colors.red),
            onPressed: () => ChunkUploadService.cancelUploadTask(task.id),
            tooltip: '取消上传',
            iconSize: 20,
            padding: EdgeInsets.zero,
            constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
          ),
      ],
    );

    // 判断文件类型
    final bool isVideo =
        fileName.toLowerCase().endsWith('.mp4') ||
        fileName.toLowerCase().endsWith('.mov') ||
        fileName.toLowerCase().endsWith('.avi');

    // 尝试从缓存中查找缩略图（使用文件名作为查找依据）
    Uint8List? thumbnailData;
    for (var asset in _assetCacheService.cachedAssets) {
      if (asset.title == fileName) {
        thumbnailData =
            _assetCacheService.hasThumbnail(asset.id)
                ? _assetCacheService.getThumbnail(asset.id)
                : null;
        break;
      }
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(color: Colors.grey.shade200)),
      ),
      child: Row(
        children: [
          // 文件缩略图
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(
              color: Colors.grey.shade200,
              borderRadius: BorderRadius.circular(6),
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(6),
              child:
                  thumbnailData != null
                      ? Image.memory(
                        thumbnailData,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return Center(
                            child:
                                isVideo
                                    ? const Icon(
                                      Icons.movie,
                                      color: Colors.orange,
                                    )
                                    : const Icon(
                                      Icons.image,
                                      color: Colors.blue,
                                    ),
                          );
                        },
                      )
                      : Center(
                        child:
                            isVideo
                                ? const Icon(Icons.movie, color: Colors.orange)
                                : const Icon(Icons.image, color: Colors.blue),
                      ),
            ),
          ),
          const SizedBox(width: 12),
          // 文件信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        fileName,
                        style: const TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 14,
                          color: Colors.black87,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    // 添加操作按钮到标题行
                    if (taskStatus == UploadTaskStatus.uploading ||
                        taskStatus == UploadTaskStatus.paused ||
                        taskStatus == UploadTaskStatus.pending ||
                        taskStatus == UploadTaskStatus.failed)
                      actionButtons,
                  ],
                ),
                // 进度条 - 放在文件名下面
                Container(
                  padding: const EdgeInsets.only(top: 4, right: 40),
                  child: LinearProgressIndicator(
                    value: displayValue,
                    backgroundColor: Colors.grey.shade200,
                    valueColor: AlwaysStoppedAnimation<Color>(statusColor),
                    minHeight: 3,
                  ),
                ),
                const SizedBox(height: 4),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '$formattedUploadedSize / $formattedSize · $displayProgress%',
                      style: TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.w400,
                        color: Colors.black54,
                      ),
                    ),
                    Text(
                      statusText,
                      style: TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.w500,
                        color: statusColor,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          // 状态指示点
          Container(
            width: 10,
            height: 10,
            decoration: BoxDecoration(
              color: statusColor,
              shape: BoxShape.circle,
            ),
          ),
        ],
      ),
    );
  }

  // 构建占位内容（加载中或无权限）
  Widget _buildPlaceholderContent() {
    // 权限检查
    if (!_hasPhotoPermission) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.no_photography, size: 64, color: Colors.grey.shade400),
            const SizedBox(height: 16),
            Text('需要照片访问权限', style: TextStyle(color: Colors.grey.shade600)),
            const SizedBox(height: 16),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: () {
                    // 打开系统设置，让用户手动授权
                    PhotoManager.openSetting();
                    // 显示提示信息
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('请在设置中授予照片访问权限，然后返回应用'),
                        duration: Duration(seconds: 5),
                      ),
                    );
                  },
                  child: const Text('授予权限'),
                ),
                const SizedBox(width: 16),
                OutlinedButton(
                  onPressed: () {
                    // 刷新权限状态
                    _checkPhotoPermission();
                    // 显示提示
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('正在刷新权限状态...'),
                        duration: Duration(seconds: 2),
                      ),
                    );
                  },
                  child: const Text('刷新'),
                ),
              ],
            ),
          ],
        ),
      );
    }

    // 加载中显示
    if (_isLoading) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text('正在加载待备份文件...'),
          ],
        ),
      );
    }

    // 默认返回空白内容
    return const SizedBox.shrink();
  }

  // 构建空状态内容
  Widget _buildEmptyStateContent() {
    // 检查是否已选择相册
    final backupState = ref.read(photoBackupProvider);
    final hasSelectedAlbums = backupState.selectedAlbums.values.any(
      (selected) => selected,
    );

    if (!hasSelectedAlbums) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.photo_album, size: 64, color: Colors.grey.shade400),
            const SizedBox(height: 16),
            Text('未选择备份相册', style: TextStyle(color: Colors.grey.shade600)),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: () {
                Navigator.pushNamed(context, '/photo-backup');
              },
              child: const Text('选择相册'),
            ),
          ],
        ),
      );
    }

    // 相册选择了，但没有文件
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.photo_library, size: 64, color: Colors.grey.shade400),
          const SizedBox(height: 16),
          Text('所选相册中没有待备份的文件', style: TextStyle(color: Colors.grey.shade600)),
          const SizedBox(height: 8),
          OutlinedButton(
            onPressed: () {
              _assetCacheService.clearCache();
              _loadRecentFiles();
            },
            child: const Text('重新扫描'),
          ),
        ],
      ),
    );
  }

  // 显示调试选项对话框
  void _showDebugOptions() {
    showModalBottomSheet(
      context: context,
      builder:
          (context) => SafeArea(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                ListTile(
                  leading: const Icon(
                    Icons.play_circle_filled,
                    color: Colors.green,
                  ),
                  title: const Text('强制开始上传'),
                  subtitle: const Text('手动启动文件上传任务'),
                  onTap: () {
                    Navigator.pop(context);
                    _forceStartUpload();
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.settings),
                  title: const Text('API设置'),
                  subtitle: const Text('配置自定义API服务器地址'),
                  onTap: () {
                    Navigator.pop(context);
                    _showApiSettingsDialog();
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.refresh),
                  title: const Text('重置备份数据'),
                  subtitle: const Text('清除所有备份相关的数据库和缓存'),
                  onTap: () {
                    Navigator.pop(context);
                    _resetBackupData();
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.clear_all),
                  title: const Text('重置文件哈希缓存'),
                  subtitle: const Text('清除文件重复检测缓存，重新检测所有文件'),
                  onTap: () {
                    Navigator.pop(context);
                    _resetHashCache();
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.cloud),
                  title: const Text('测试API连接'),
                  subtitle: const Text('检查API服务器连接状态'),
                  onTap: () {
                    Navigator.pop(context);
                    _testApiConnection();
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.info_outline),
                  title: const Text('打印调试信息'),
                  subtitle: const Text('在控制台输出当前上传状态信息'),
                  onTap: () {
                    Navigator.pop(context);
                    _printDebugInfo();
                  },
                ),
              ],
            ),
          ),
    );
  }

  // 显示API设置对话框
  void _showApiSettingsDialog() async {
    // 获取当前配置
    final photoBackupService = ref.read(photoBackupServiceProvider);
    final apiConfig = await photoBackupService.checkApiConfig();

    // 控制器
    final hostController = TextEditingController(
      text: apiConfig['host'] as String? ?? '',
    );
    final portController = TextEditingController(
      text: (apiConfig['port'] as dynamic?)?.toString() ?? '8000',
    );
    final protocolController = TextEditingController(
      text: apiConfig['protocol'] as String? ?? 'http',
    );
    final prefixController = TextEditingController(
      text: apiConfig['path_prefix'] as String? ?? '/api',
    );

    // 是否使用自定义设置
    bool useCustomSettings = apiConfig['isCustom'] == true;

    await showDialog(
      context: context,
      builder:
          (context) => StatefulBuilder(
            builder:
                (context, setState) => AlertDialog(
                  title: const Text('API服务器设置'),
                  content: SingleChildScrollView(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SwitchListTile(
                          title: const Text('使用自定义API设置'),
                          value: useCustomSettings,
                          onChanged: (value) {
                            setState(() {
                              useCustomSettings = value;
                            });
                          },
                        ),
                        const Divider(),
                        if (useCustomSettings) ...[
                          TextField(
                            controller: hostController,
                            decoration: const InputDecoration(
                              labelText: '服务器地址',
                              hintText: '例如: 192.168.1.100',
                            ),
                            enabled: useCustomSettings,
                          ),
                          TextField(
                            controller: portController,
                            decoration: const InputDecoration(
                              labelText: '端口',
                              hintText: '例如: 8000',
                            ),
                            keyboardType: TextInputType.number,
                            enabled: useCustomSettings,
                          ),
                          TextField(
                            controller: protocolController,
                            decoration: const InputDecoration(
                              labelText: '协议',
                              hintText: '例如: http',
                            ),
                            enabled: useCustomSettings,
                          ),
                          TextField(
                            controller: prefixController,
                            decoration: const InputDecoration(
                              labelText: '路径前缀',
                              hintText: '例如: /api',
                            ),
                            enabled: useCustomSettings,
                          ),
                        ] else ...[
                          const Text('当前使用默认配置:'),
                          Text(
                            '服务器: ${apiConfig['host']}:${apiConfig['port']}',
                          ),
                          Text('协议: ${apiConfig['protocol']}'),
                          Text('路径前缀: ${apiConfig['path_prefix']}'),
                        ],
                      ],
                    ),
                  ),
                  actions: [
                    TextButton(
                      onPressed: () => Navigator.of(context).pop(),
                      child: const Text('取消'),
                    ),
                    TextButton(
                      onPressed: () async {
                        if (useCustomSettings) {
                          try {
                            // 构建配置
                            final newConfig = {
                              'host': hostController.text,
                              'port': int.tryParse(portController.text) ?? 8000,
                              'protocol': protocolController.text,
                              'path_prefix': prefixController.text,
                              'timeout': 15000,
                              'retries': 3,
                            };

                            // 保存配置
                            await _saveApiConfig(newConfig, true);

                            if (context.mounted) {
                              Navigator.of(context).pop();
                              ScaffoldMessenger.of(context).showSnackBar(
                                const SnackBar(
                                  content: Text('API设置已保存，重启应用后生效'),
                                ),
                              );
                            }
                          } catch (e) {
                            if (context.mounted) {
                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(content: Text('保存设置失败: $e')),
                              );
                            }
                          }
                        } else {
                          // 禁用自定义设置
                          await _saveApiConfig(null, false);
                          if (context.mounted) {
                            Navigator.of(context).pop();
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(
                                content: Text('已恢复默认API设置，重启应用后生效'),
                              ),
                            );
                          }
                        }
                      },
                      child: const Text('保存'),
                    ),
                  ],
                ),
          ),
    );
  }

  // 保存API配置
  Future<void> _saveApiConfig(
    Map<String, dynamic>? config,
    bool enabled,
  ) async {
    try {
      final userConfig = ConfigLoader().userConfig;
      await userConfig.setApiConfig(config);
      await userConfig.setEnabled(enabled);
    } catch (e) {
      debugPrint('保存API配置失败: $e');
      rethrow;
    }
  }

  // 重置备份数据
  Future<void> _resetBackupData() async {
    // 确认对话框
    final confirmed =
        await showDialog<bool>(
          context: context,
          builder:
              (context) => AlertDialog(
                title: const Text('确认重置'),
                content: const Text('此操作将清除所有备份相关的数据库和缓存，不会影响原始相册文件。确定要继续吗？'),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(false),
                    child: const Text('取消'),
                  ),
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(true),
                    style: TextButton.styleFrom(foregroundColor: Colors.red),
                    child: const Text('确定重置'),
                  ),
                ],
              ),
        ) ??
        false;

    if (!confirmed) return;

    // 显示加载对话框
    showDialog(
      context: context,
      barrierDismissible: false,
      builder:
          (context) => const AlertDialog(
            content: Row(
              children: [
                CircularProgressIndicator(),
                SizedBox(width: 20),
                Text('正在重置备份数据...'),
              ],
            ),
          ),
    );

    try {
      final photoBackupService = ref.read(photoBackupServiceProvider);
      await photoBackupService.cleanupBackupData();

      // 刷新相册缓存
      ref.read(photoBackupProvider.notifier).clearAlbumCache();

      // 关闭加载对话框
      if (context.mounted) {
        Navigator.of(context).pop();
      }

      // 显示成功对话框
      if (context.mounted) {
        showDialog(
          context: context,
          builder:
              (context) => AlertDialog(
                title: const Text('重置成功'),
                content: const Text('所有备份相关的数据库和缓存已清除，您可以重新开始备份操作。'),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(),
                    child: const Text('确定'),
                  ),
                ],
              ),
        );
      }

      // 刷新页面数据
      _refreshData();
    } catch (e) {
      // 关闭加载对话框
      if (context.mounted) {
        Navigator.of(context).pop();
      }

      // 显示错误对话框
      if (context.mounted) {
        showDialog(
          context: context,
          builder:
              (context) => AlertDialog(
                title: const Text('重置失败'),
                content: Text('错误信息: $e'),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(),
                    child: const Text('关闭'),
                  ),
                ],
              ),
        );
      }
    }
  }

  // 测试API连接
  Future<void> _testApiConnection() async {
    final photoBackupService = ref.read(photoBackupServiceProvider);

    // 显示加载对话框
    showDialog(
      context: context,
      barrierDismissible: false,
      builder:
          (context) => const AlertDialog(
            content: Row(
              children: [
                CircularProgressIndicator(),
                SizedBox(width: 20),
                Text('正在测试API连接...'),
              ],
            ),
          ),
    );

    try {
      // 获取API配置
      final apiConfig = await photoBackupService.checkApiConfig();

      // 关闭加载对话框
      if (context.mounted) {
        Navigator.of(context).pop();
      }

      // 显示结果对话框
      if (context.mounted) {
        showDialog(
          context: context,
          builder:
              (context) => AlertDialog(
                title: const Text('API连接测试结果'),
                content: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text('API地址: ${apiConfig['apiUrl']}'),
                      Text('环境: ${apiConfig['environment']}'),
                      Text('协议: ${apiConfig['protocol']}'),
                      Text('主机: ${apiConfig['host']}'),
                      Text('端口: ${apiConfig['port']}'),
                      Text('前缀: ${apiConfig['path_prefix']}'),
                      const Divider(),
                      Text(
                        '连接状态: ${apiConfig['canConnect'] == true ? '✅ 成功' : '❌ 失败'}',
                      ),
                      if (apiConfig['statusCode'] != null)
                        Text('状态码: ${apiConfig['statusCode']}'),
                      if (apiConfig['error'] != null)
                        Text(
                          '错误: ${apiConfig['error']}',
                          style: const TextStyle(color: Colors.red),
                        ),
                    ],
                  ),
                ),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(),
                    child: const Text('关闭'),
                  ),
                ],
              ),
        );
      }
    } catch (e) {
      // 关闭加载对话框
      if (context.mounted) {
        Navigator.of(context).pop();
      }

      // 显示错误对话框
      if (context.mounted) {
        showDialog(
          context: context,
          builder:
              (context) => AlertDialog(
                title: const Text('API连接测试失败'),
                content: Text('错误信息: $e'),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(),
                    child: const Text('关闭'),
                  ),
                ],
              ),
        );
      }
    }
  }

  // 构建文件列表
  Widget _buildFilesList() {
    // 检查权限
    if (!_hasPhotoPermission) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.no_photography, size: 64, color: Colors.grey.shade400),
            const SizedBox(height: 16),
            Text('需要照片访问权限', style: TextStyle(color: Colors.grey.shade600)),
            const SizedBox(height: 16),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: () {
                    // 打开系统设置，让用户手动授权
                    PhotoManager.openSetting();
                    // 显示提示信息
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('请在设置中授予照片访问权限，然后返回应用'),
                        duration: Duration(seconds: 5),
                      ),
                    );
                  },
                  child: const Text('授予权限'),
                ),
                const SizedBox(width: 16),
                OutlinedButton(
                  onPressed: () {
                    // 刷新权限状态
                    _checkPhotoPermission();
                    // 显示提示
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('正在刷新权限状态...'),
                        duration: Duration(seconds: 2),
                      ),
                    );
                  },
                  child: const Text('刷新'),
                ),
              ],
            ),
          ],
        ),
      );
    }

    if (_isLoading) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text('正在加载待备份文件...'),
          ],
        ),
      );
    }

    // 获取活动任务 - 限制数量以提高性能
    final activeTasks =
        ChunkUploadService.uploadTasks
            .where(
              (task) =>
                  task.status == UploadTaskStatus.pending ||
                  task.status == UploadTaskStatus.uploading ||
                  task.status == UploadTaskStatus.paused,
            )
            .take(20) // 限制最多显示20个任务
            .toList();

    if (_recentAssets.isEmpty && activeTasks.isEmpty) {
      // 检查是否已选择相册
      final backupState = ref.read(photoBackupProvider);
      final hasSelectedAlbums = backupState.selectedAlbums.values.any(
        (selected) => selected,
      );

      if (!hasSelectedAlbums) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.photo_album, size: 64, color: Colors.grey.shade400),
              const SizedBox(height: 16),
              Text('未选择备份相册', style: TextStyle(color: Colors.grey.shade600)),
              const SizedBox(height: 8),
              ElevatedButton(
                onPressed: () {
                  Navigator.pushNamed(context, '/photo-backup');
                },
                child: const Text('选择相册'),
              ),
            ],
          ),
        );
      }

      // 相册选择了，但没有文件
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.photo_library, size: 64, color: Colors.grey.shade400),
            const SizedBox(height: 16),
            Text(
              '所选相册中没有待备份的文件',
              style: TextStyle(color: Colors.grey.shade600),
            ),
            const SizedBox(height: 8),
            OutlinedButton(
              onPressed: () {
                _assetCacheService.clearCache();
                _loadRecentFiles();
              },
              child: const Text('重新扫描'),
            ),
          ],
        ),
      );
    }

    // 限制项目数量，避免渲染太多导致卡顿
    final limitedAssets = _recentAssets.take(20).toList(); // 最多显示20个待备份资产

    return ListView(
      children: [
        // 显示活动上传任务
        if (activeTasks.isNotEmpty) ...[
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: Text(
              '正在上传',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: Colors.black,
              ),
            ),
          ),
          ...activeTasks.map((task) => _buildTaskItem(task)),
          const Divider(height: 24),
        ],

        // 显示待上传文件
        if (limitedAssets.isNotEmpty) ...[
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: Text(
              '待上传文件',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: Colors.black,
              ),
            ),
          ),
          ...limitedAssets.map((asset) => _buildAssetItem(asset)),

          // 如果有更多资产未显示，显示提示
          if (_recentAssets.length > limitedAssets.length)
            Padding(
              padding: const EdgeInsets.all(16),
              child: Center(
                child: Text(
                  '还有 ${_recentAssets.length - limitedAssets.length} 个文件未显示',
                  style: TextStyle(color: Colors.grey.shade600),
                ),
              ),
            ),
        ],
      ],
    );
  }

  // 构建待上传资源项
  Widget _buildAssetItem(AssetEntity asset) {
    // 文件名
    String fileName = asset.title ?? '未知文件';

    // 检查是否正在上传 - 只检查一次，避免频繁调用
    final bool isUploading = _photoBackupService.isAssetUploading(asset.id);

    // 使用缓存的缩略图
    final hasCachedThumb = _assetCacheService.hasThumbnail(asset.id);
    final cachedThumb =
        hasCachedThumb ? _assetCacheService.getThumbnail(asset.id) : null;

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(color: Colors.grey.shade200)),
      ),
      child: Row(
        children: [
          // 文件缩略图
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(
              color: Colors.grey.shade200,
              borderRadius: BorderRadius.circular(6),
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(6),
              child:
                  hasCachedThumb
                      ? Image.memory(
                        cachedThumb!,
                        fit: BoxFit.cover,
                        // 添加缓存和错误处理
                        errorBuilder: (context, error, stackTrace) {
                          return Center(
                            child:
                                asset.type == AssetType.image
                                    ? const Icon(
                                      Icons.image,
                                      color: Colors.blue,
                                    )
                                    : const Icon(
                                      Icons.movie,
                                      color: Colors.orange,
                                    ),
                          );
                        },
                      )
                      : Center(
                        child:
                            asset.type == AssetType.image
                                ? const Icon(Icons.image, color: Colors.blue)
                                : const Icon(Icons.movie, color: Colors.orange),
                      ),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  fileName,
                  style: const TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 14,
                    color: Colors.black87,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 4),
                // 使用FutureBuilder获取文件大小，避免多个ValueNotifier
                FutureBuilder<String>(
                  future: _getAssetFileSize(asset),
                  initialData: '计算中...',
                  builder: (context, snapshot) {
                    return Text(
                      '${snapshot.data} · ${_formatDate(asset.createDateTime)}',
                      style: TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.w400,
                        color: Colors.black54,
                      ),
                    );
                  },
                ),
                const SizedBox(height: 2),
                // 简化状态显示，减少Timer使用
                Text(
                  isUploading ? '上传中' : '等待备份',
                  style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w500,
                    color: isUploading ? Colors.green[600] : Colors.blue[600],
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(width: 12),
          Container(
            width: 10,
            height: 10,
            decoration: BoxDecoration(
              color: isUploading ? Colors.green : Colors.blue,
              shape: BoxShape.circle,
            ),
          ),
        ],
      ),
    );
  }

  // 获取资产文件大小的方法
  Future<String> _getAssetFileSize(AssetEntity asset) async {
    try {
      final file = await asset.file;
      if (file != null) {
        return _formatFileSize(file.lengthSync());
      }
    } catch (e) {
      print('获取文件大小失败: $e');
    }
    return '未知大小';
  }

  // 格式化文件大小
  String _formatFileSize(int size) {
    if (size < 1024) return '$size B';
    if (size < 1024 * 1024) return '${(size / 1024).toStringAsFixed(1)} KB';
    if (size < 1024 * 1024 * 1024) {
      return '${(size / (1024 * 1024)).toStringAsFixed(1)} MB';
    }
    return '${(size / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
  }

  // 格式化日期
  String _formatDate(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')}';
  }

  // 计算选中相册的文件总数
  int _calculateTotalFiles(PhotoBackupState backupState) {
    int totalCount = 0;
    for (var album in backupState.albumCache) {
      if (backupState.selectedAlbums[album.id] == true) {
        totalCount += album.getValidCount(
          backupState.autoBackupPhotos,
          backupState.autoBackupVideos,
        );
      }
    }
    return totalCount;
  }

  // 构建任务项的优化版本
  Widget _buildTaskItem(UploadTask task) {
    // 缓存状态和进度，避免频繁状态计算
    final taskStatus = task.status;
    final fileName = task.fileName ?? '未知文件';
    final fileSize = task.fileSize ?? 0;
    final uploadedBytes = task.uploadedBytes;

    // 计算实际进度比例（0-1之间）
    final actualProgress = uploadedBytes / fileSize;
    // 使用实际进度或task.progress中较大的值，确保显示合理
    final displayValue = math.max(
      // 如果progress值大于1，则将其视为百分比并转换为0-1之间的值
      (task.progress > 1 ? task.progress / 100 : task.progress).clamp(0.0, 1.0),
      actualProgress.clamp(0.0, 1.0),
    );

    // 使用已有的_formatFileSize方法
    final formattedSize = _formatFileSize(fileSize);
    final formattedUploadedSize = _formatFileSize(uploadedBytes);

    // 计算百分比进度，显示时使用
    final progressPercent = (displayValue * 100).clamp(0.0, 100.0);

    // 状态文本映射表 - 使用正确的枚举值
    final statusText =
        {
          UploadTaskStatus.pending: '等待上传',
          UploadTaskStatus.uploading: '上传中',
          UploadTaskStatus.paused: '已暂停',
          UploadTaskStatus.completed: '已完成',
          UploadTaskStatus.failed: '上传失败',
          UploadTaskStatus.canceled: '已取消',
        }[taskStatus] ??
        '未知状态';

    // 状态颜色映射表 - 使用正确的枚举值
    final statusColor =
        {
          UploadTaskStatus.pending: Colors.grey,
          UploadTaskStatus.uploading: Colors.blue,
          UploadTaskStatus.paused: Colors.orange,
          UploadTaskStatus.completed: Colors.green,
          UploadTaskStatus.failed: Colors.red,
          UploadTaskStatus.canceled: Colors.grey,
        }[taskStatus] ??
        Colors.grey;

    // 显示的进度值，保留1位小数
    final displayProgress = progressPercent.toStringAsFixed(1);

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 文件名和大小
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // 使用Expanded包裹文件名，防止溢出
                Expanded(
                  child: Text(
                    fileName,
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Text(
                  formattedSize,
                  style: TextStyle(color: Colors.grey.shade600, fontSize: 14),
                ),
              ],
            ),

            const SizedBox(height: 8),

            // 进度条 - 确保值在0-1之间
            LinearProgressIndicator(
              value: displayValue,
              backgroundColor: Colors.grey.shade200,
              valueColor: AlwaysStoppedAnimation<Color>(statusColor),
            ),

            const SizedBox(height: 8),

            // 状态和进度文本
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  statusText,
                  style: TextStyle(
                    color: statusColor,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Text(
                  '$displayProgress% · $formattedUploadedSize/$formattedSize',
                  style: const TextStyle(fontWeight: FontWeight.w500),
                ),
              ],
            ),

            const SizedBox(height: 8),

            // 操作按钮 - 使用ChunkUploadService的静态方法
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                // 根据状态显示不同的按钮
                if (taskStatus == UploadTaskStatus.uploading)
                  IconButton(
                    icon: const Icon(Icons.pause, color: Colors.orange),
                    onPressed:
                        () => ChunkUploadService.pauseUploadTask(task.id),
                    tooltip: '暂停上传',
                    iconSize: 20,
                  ),
                if (taskStatus == UploadTaskStatus.paused)
                  IconButton(
                    icon: const Icon(Icons.play_arrow, color: Colors.green),
                    onPressed:
                        () => ChunkUploadService.resumeUploadTask(task.id),
                    tooltip: '继续上传',
                    iconSize: 20,
                  ),
                if (taskStatus == UploadTaskStatus.pending ||
                    taskStatus == UploadTaskStatus.paused ||
                    taskStatus == UploadTaskStatus.failed)
                  IconButton(
                    icon: const Icon(Icons.delete, color: Colors.red),
                    onPressed:
                        () => ChunkUploadService.cancelUploadTask(task.id),
                    tooltip: '取消上传',
                    iconSize: 20,
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 打印未完成相册信息和相册缓存数据
  Future<void> _printDebugInfo() async {
    // 提高性能：仅在调试时运行，并且整个方法使用microtask
    assert(() {
      // 将整个方法放在microtask中执行，避免阻塞UI
      Future.microtask(() {
        try {
          debugPrint('====== 调试信息 - 相册和进度记录 ======');

          // 任务1：获取相册信息（并发）
          Future(() async {
            try {
              // 打印相册缓存信息
              final backupState = ref.read(photoBackupProvider);
              final selectedAlbumInfos =
                  backupState.albumCache
                      .where(
                        (album) => backupState.selectedAlbums[album.id] == true,
                      )
                      .toList();

              debugPrint(
                '相册缓存: 总数量=${backupState.albumCache.length}，已选中=${selectedAlbumInfos.length}',
              );

              // 仅列出前5个相册，避免输出过多信息
              final albumsToShow = selectedAlbumInfos.take(5).toList();
              if (albumsToShow.isNotEmpty) {
                debugPrint('选中相册列表(前5个):');
                for (int i = 0; i < albumsToShow.length; i++) {
                  final album = albumsToShow[i];
                  debugPrint(
                    '${i + 1}. ${album.name}: 照片=${album.imageCount}，视频=${album.videoCount}',
                  );
                }

                if (selectedAlbumInfos.length > 5) {
                  debugPrint('... 还有 ${selectedAlbumInfos.length - 5} 个相册未显示');
                }
              }
            } catch (e) {
              debugPrint('获取相册信息时出错: $e');
            }
          });

          // 任务2：获取上传状态信息（并发）
          Future(() async {
            try {
              // 打印未完成上传任务
              final incompleteAlbums =
                  await _photoBackupService
                      .getProgressService()
                      .getIncompleteAlbums();
              debugPrint('未完成相册上传任务: ${incompleteAlbums.length}个');

              // 仅显示前3个未完成相册
              final albumsToShow = incompleteAlbums.take(3).toList();
              for (int i = 0; i < albumsToShow.length; i++) {
                final album = albumsToShow[i];
                debugPrint(
                  '${i + 1}. ID=${album.albumId}, 名称=${album.albumName}, 已处理=${album.processedCount}, 是否完成=${album.isCompleted}',
                );
              }

              if (incompleteAlbums.length > 3) {
                debugPrint('... 还有 ${incompleteAlbums.length - 3} 个未完成相册未显示');
              }
            } catch (e) {
              debugPrint('获取进度记录时出错: $e');
            }
          });

          // 任务3：打印当前上传任务状态（并发）
          Future(() async {
            try {
              final allTasks = ChunkUploadService.uploadTasks;

              // 筛选出不同状态的任务
              final pendingTasks =
                  allTasks
                      .where((t) => t.status == UploadTaskStatus.pending)
                      .toList();
              final uploadingTasks =
                  allTasks
                      .where((t) => t.status == UploadTaskStatus.uploading)
                      .toList();
              final failedTasks =
                  allTasks
                      .where((t) => t.status == UploadTaskStatus.failed)
                      .toList();
              final completedTasks =
                  allTasks
                      .where((t) => t.status == UploadTaskStatus.completed)
                      .toList();

              debugPrint('当前上传任务情况:');
              debugPrint(
                '总计: ${allTasks.length}, 等待: ${pendingTasks.length}, 上传中: ${uploadingTasks.length}, 已完成: ${completedTasks.length}, 失败: ${failedTasks.length}',
              );

              // 打印最近的失败任务信息
              if (failedTasks.isNotEmpty) {
                debugPrint('最近3个失败任务:');
                final tasksToShow = failedTasks.take(3).toList();
                for (int i = 0; i < tasksToShow.length; i++) {
                  final task = tasksToShow[i];
                  debugPrint(
                    '${i + 1}. 文件: ${task.fileName}, 错误: ${task.error ?? "未知错误"}',
                  );
                }
              }
            } catch (e) {
              debugPrint('获取上传任务状态时出错: $e');
            }
          });

          // 最后的消息
          Future.delayed(const Duration(seconds: 1), () {
            debugPrint('====== 调试信息结束 ======');
          });
        } catch (e) {
          debugPrint('调试信息收集过程中发生错误: $e');
          debugPrint('====== 调试信息结束（带错误）======');
        }
      });

      return true;
    }());

    // 在非调试模式下不做任何操作
    return;
  }

  // 构建进度信息区域
  Widget _buildProgressInfo(int totalCount) {
    return Container(
      padding: const EdgeInsets.all(16),
      color: Colors.blue.shade50,
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '自动备份 - 剩余文件 $totalCount 个',
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Colors.black,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            '最大并行数: ${ref.read(photoBackupProvider).parallelBackupCount}个文件',
            style: const TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              color: Colors.black87,
            ),
          ),
        ],
      ),
    );
  }

  // 刷新数据 - 带超时和更好的错误处理
  Future<void> _refreshData() async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
    });

    try {
      // 设置超时保护
      final refreshCompleter = Completer<void>();

      // 超时保护 - 5秒后自动结束加载状态
      Future.delayed(const Duration(seconds: 5), () {
        if (!refreshCompleter.isCompleted) {
          debugPrint('刷新数据超时');
          if (mounted) {
            ScaffoldMessenger.of(
              context,
            ).showSnackBar(const SnackBar(content: Text('加载超时，请稍后重试')));
            setState(() {
              _isLoading = false;
            });
          }
          refreshCompleter.complete();
        }
      });

      // 在单独的microtask中执行耗时操作
      Future.microtask(() async {
        try {
          // 检查权限
          await _checkPhotoPermission();

          if (!_hasPhotoPermission) {
            debugPrint('无照片权限，无法刷新数据');
            if (mounted && !refreshCompleter.isCompleted) {
              refreshCompleter.complete();
              setState(() {
                _isLoading = false;
              });
            }
            return;
          }

          // 执行数据加载
          await _loadRecentFiles();

          if (!refreshCompleter.isCompleted) {
            refreshCompleter.complete();
          }
        } catch (e) {
          debugPrint('刷新数据失败: $e');
          if (!refreshCompleter.isCompleted) {
            refreshCompleter.complete();
          }
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(
                  '加载失败: ${e.toString().substring(0, math.min(50, e.toString().length))}',
                ),
              ),
            );
            setState(() {
              _isLoading = false;
            });
          }
        }
      });

      // 等待操作完成或超时
      await refreshCompleter.future;
    } catch (e) {
      debugPrint('刷新数据外部异常: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              '出现异常: ${e.toString().substring(0, math.min(50, e.toString().length))}',
            ),
          ),
        );
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  // 构建资产列表
  Widget _buildAssetsList() {
    return _buildFilesList();
  }

  // 重置文件哈希缓存
  Future<void> _resetHashCache() async {
    // 确认对话框
    final confirmed =
        await showDialog<bool>(
          context: context,
          builder:
              (context) => AlertDialog(
                title: const Text('确认重置'),
                content: const Text('此操作将清除文件重复检测缓存，允许重新检测所有文件。是否继续？'),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(false),
                    child: const Text('取消'),
                  ),
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(true),
                    style: TextButton.styleFrom(foregroundColor: Colors.red),
                    child: const Text('确定重置'),
                  ),
                ],
              ),
        ) ??
        false;

    if (!confirmed) return;

    // 显示加载对话框
    showDialog(
      context: context,
      barrierDismissible: false,
      builder:
          (context) => const AlertDialog(
            content: Row(
              children: [
                CircularProgressIndicator(),
                SizedBox(width: 20),
                Text('正在重置文件哈希缓存...'),
              ],
            ),
          ),
    );

    try {
      final photoBackupService = ref.read(photoBackupServiceProvider);
      // 仅重置文件哈希服务
      await photoBackupService.resetFileHashCache();

      // 关闭加载对话框
      if (context.mounted) {
        Navigator.of(context).pop();
      }

      // 显示成功对话框
      if (context.mounted) {
        showDialog(
          context: context,
          builder:
              (context) => AlertDialog(
                title: const Text('重置成功'),
                content: const Text('文件哈希缓存已清除，系统将在下次扫描时重新检测所有文件。'),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(),
                    child: const Text('确定'),
                  ),
                ],
              ),
        );
      }

      // 刷新页面数据
      _refreshData();
    } catch (e) {
      // 关闭加载对话框
      if (context.mounted) {
        Navigator.of(context).pop();
      }

      // 显示错误对话框
      if (context.mounted) {
        showDialog(
          context: context,
          builder:
              (context) => AlertDialog(
                title: const Text('重置失败'),
                content: Text('错误信息: $e'),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(),
                    child: const Text('关闭'),
                  ),
                ],
              ),
        );
      }
    }
  }

  // 强制开始上传
  Future<void> _forceStartUpload() async {
    // 先刷新待上传文件列表
    await _refreshData();

    if (_recentAssets.isEmpty) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('没有待上传的文件')));
      return;
    }

    // 显示加载对话框
    showDialog(
      context: context,
      barrierDismissible: false,
      builder:
          (context) => const AlertDialog(
            content: Row(
              children: [
                CircularProgressIndicator(),
                SizedBox(width: 20),
                Text('正在准备上传文件...'),
              ],
            ),
          ),
    );

    try {
      debugPrint('手动强制开始上传，${_recentAssets.length}个文件');

      // 将耗时操作放到后台线程
      await Future(() async {
        // 重置备份状态，确保之前挂起的状态不会影响本次上传
        _photoBackupService.resetBackupStatus();

        // 设置设备模型，确保上传不会因为设备名称为空而失败
        _photoBackupService.setDeviceModel(
          Platform.isAndroid ? 'Android设备' : 'iOS设备',
        );

        // 确保自动备份已启用
        if (!_photoBackupService.isAutoBackupEnabled(
          ref.read(photoBackupProvider),
        )) {
          debugPrint('强制启用自动备份设置');
          ref.read(photoBackupProvider.notifier).setAutoBackupPhotos(true);
          ref.read(photoBackupProvider.notifier).setAutoBackupVideos(true);
        }

        // 直接开始批量上传 - 这里将文件列表副本传递给上传方法
        final filesToUpload = List<AssetEntity>.from(_recentAssets);
        await _photoBackupService.startBatchUpload(ref, filesToUpload);
      });

      // 关闭对话框
      if (context.mounted) {
        Navigator.pop(context);
      }

      // 刷新UI
      if (mounted) {
        setState(() {
          _streamKey = UniqueKey();
        });

        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('已开始上传')));
      }
    } catch (e) {
      // 关闭对话框
      if (context.mounted) {
        Navigator.pop(context);
      }

      debugPrint('强制开始上传失败: $e');
      if (context.mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('上传失败: $e')));
      }
    }
  }
}
